package com.newlink.building.userinfo.activity

import android.Manifest
import android.content.DialogInterface
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.provider.Settings
import android.util.Log
import android.view.Gravity
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import com.newlink.building.library_rino.ConnectionController
import com.google.android.material.snackbar.Snackbar
import com.newlink.building.common_base.base.NL_BaseMvpActivity
import com.newlink.building.common_base.event.CallCreateActionBean
import com.newlink.building.common_base.event.CallCreateBean
import com.newlink.building.common_base.event.MessageEvent
import com.newlink.building.common_base.event.TYPE_CALL_SEND_CREATE_CHANNEL_REQUEST_PROPERTY_MANAGER
import com.newlink.building.common_base.event.TYPE_CALL_SEND_CREATE_CHANNEL_RESULT_PROPERTY_MANAGER
import com.newlink.building.common_base.event.TokenVo
import com.newlink.building.common_base.ext.setNewOrAddData
import com.newlink.building.common_base.ext.showToast
import com.newlink.building.common_base.model.bean.PropertyManagerData
import com.newlink.building.common_base.utils.DialogUtil
import com.newlink.building.common_base.utils.NLog
import com.newlink.building.common_base.utils.PermissionHelper
import com.newlink.building.NL_App.Companion.coreContext
import com.newlink.building.manager.Module_Phone_VoipController
import com.newlink.building.userinfo.R
import com.newlink.building.userinfo.adapter.Module_UserInfo_PropertyManagementAdapter
import com.newlink.building.userinfo.databinding.ActivityFamilyManagementBinding
import com.newlink.building.userinfo.mvp.Module_UserInfo_PropertyManagementPresenter
import com.newlink.building.userinfo.mvp.contract.Module_UserInfo_PropertyManagementContract
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.linphone.core.Call
import org.linphone.core.Core
import org.linphone.core.CoreListenerStub

/**
 * @author wangyang
 * @date 2022/9/16
 * @description 我的——家庭管理页面
 */
class Module_UserInfo_PropertyManagementActivityNL :
    NL_BaseMvpActivity<Module_UserInfo_PropertyManagementContract.View, Module_UserInfo_PropertyManagementContract.Presenter>(),
    Module_UserInfo_PropertyManagementContract.View, View.OnClickListener {

    private var curList: MutableList<PropertyManagerData> = ArrayList()
    var mAdapter: Module_UserInfo_PropertyManagementAdapter = Module_UserInfo_PropertyManagementAdapter(mutableListOf())
    var curPage: Int = 1
    var curLimit: Int = 20
    private var emptyContent: View? = null
    var localChannelName: String = ""
    var tokenVo: TokenVo? = null
    var mPropertyManagerData: PropertyManagerData? = null

    private lateinit var mBinding: ActivityFamilyManagementBinding
    override fun attachLayoutRes(): View {
        mBinding = ActivityFamilyManagementBinding.inflate(layoutInflater)
        return mBinding.root
    }

    override fun initData() {
        mPresenter?.getPropertyUserList(accessToken, userInfoData.prjId, "")
    }

    override fun initView() {
        super.initView()
        initCallErrorMessage()
        emptyContent = findViewById(R.id.empty_content)
        findViewById<TextView>(R.id.tv_title_bar_center).text =
            resources.getText(R.string.property_management)

        findViewById<ImageView>(R.id.iv_title_bar_right).setOnClickListener(this)
        mBinding.rvFamilyManagement.adapter = mAdapter
        mAdapter.setOnItemChildClickListener { adapter, view, position ->
            when (view.id) {
                R.id.iv_call -> {
                    mPropertyManagerData = mAdapter.getItem(position)
                    if (!PermissionHelper.required(this)
                            .hasPermission(Manifest.permission.RECORD_AUDIO)
                    ) {
                        requestPermissions(arrayOf(Manifest.permission.RECORD_AUDIO), 0)
                    } else {
                        sendCreateChannelEvent()
                    }
                }
            }
        }
        coreContext.core.addListener(coreListener)
    }

    private val coreListener = object : CoreListenerStub() {
        override fun onCallStateChanged(
            core: Core,
            call: Call,
            state: Call.State,
            message: String,
        ) {
            when (state) {
                /**
                 * 由于在coreContext里OutgoingInit时会确保清除ChannelName,家庭成员呼叫是自己创建的ChannelName需要重新设置一下
                 */
                Call.State.OutgoingProgress -> {
                    if (localChannelName.isNotEmpty()) {
                        ConnectionController.getInstance(this@Module_UserInfo_PropertyManagementActivityNL)
                            .setRemoteChannelName(localChannelName)
                    }
                    if (tokenVo != null) {
                        ConnectionController.getInstance(this@Module_UserInfo_PropertyManagementActivityNL)
                            .convert2AgoraUserToken(tokenVo, agoraId, agoraAppId)
                    }
                }

                else -> {}
            }
        }
    }

    fun sendCreateChannelEvent() {
        if (Module_Phone_VoipController.get().isCallingState()) {
            showToast(getString(R.string.outgoing_call_not_invite_again))
            return
        }
        val sipMsgEvent = MessageEvent(
            TYPE_CALL_SEND_CREATE_CHANNEL_REQUEST_PROPERTY_MANAGER,
            CallCreateActionBean(aid = agoraId)
        )
        EventBus.getDefault().post(sipMsgEvent)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventMsgReceived(event: MessageEvent) {
        when (event.msgType) {
            TYPE_CALL_SEND_CREATE_CHANNEL_RESULT_PROPERTY_MANAGER -> {
                Log.e("RoomUserActivity", "TYPE_CALL_SEND_CREATE_CHANNEL_RESULT_PROPERTY_MANAGER")
                val callCreateBean = event.msgContent as CallCreateBean?
                localChannelName = callCreateBean?.data?.rtcToken?.channelName.orEmpty()
                tokenVo = callCreateBean?.data
                makeCall()
            }
        }
    }

    private fun makeCall() {
        Module_Phone_VoipController.get()
            .makeAudioCall(mPropertyManagerData?.aid.toString(), mPropertyManagerData?.name)
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray,
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == 0) {
            val granted =
                grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED
            if (granted) {
                sendCreateChannelEvent()
            } else {
                showPermissionDialog()

            }
        }
    }

    private fun showPermissionDialog() {
        val mDialog = DialogUtil.getConfirmDialog(
            this,
            getString(R.string.permission_content_audio),
            object : DialogInterface.OnClickListener {
                override fun onClick(dialog: DialogInterface?, which: Int) {
                    val intent = Intent()
                    intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
                    val uri = Uri.fromParts("package", packageName, null)
                    intent.data = uri
                    startActivity(intent)
                }
            },
            object : DialogInterface.OnClickListener {
                override fun onClick(dialog: DialogInterface?, which: Int) {

                }
            }).show()
        mDialog.window?.run {
            attributes = attributes.apply {
                width = (windowManager.defaultDisplay.width * 0.95).toInt()
                gravity = Gravity.CENTER
            }
        }
    }


    override fun initRestoreInstanceState(savedInstanceState: Bundle) {
        finish()
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.iv_title_bar_right -> {
                //添加家庭成员
//                startActivity(Intent(this, FamilyManagementAddActivity::class.java))
            }
        }
    }

    override fun onResume() {
        super.onResume()
//        mPresenter?.getFamilyMaxMemberCount(accessToken , masterUserId=userId , prjType = userInfoData.prjType)

    }

    private fun initAdapter(list: MutableList<PropertyManagerData>) {

        curList.clear()
        curList = list

        val tempList = ArrayList<PropertyManagerData>()
        for (temp in curList) {
            if (temp.id != "$userId") {
                tempList.add(temp)
            } else {
                NLog.e("家庭列表发现自己,跳过~~")
            }
        }

//        if (mAdapter == null) {
//            mAdapter = PropertyManagementAdapter(tempList)
//            mAdapter?.addChildClickViewIds(
//                R.id.cl
//            )
//            mBinding.rvFamilyManagement.adapter = mAdapter
//        }
        mAdapter?.setNewOrAddData(true, tempList)

        if (tempList.size == 0) {
            emptyContent?.visibility = View.VISIBLE
            mBinding.rvFamilyManagement.visibility = View.GONE
        } else {
            emptyContent?.visibility = View.GONE
            mBinding.rvFamilyManagement.visibility = View.VISIBLE
        }
    }

    override fun createPresenter() = Module_UserInfo_PropertyManagementPresenter()
    override fun getPropertyUserListSuccess(data: MutableList<PropertyManagerData>) {
        val copyList = data.toMutableList()
        try {
            copyList.sortBy { it.aid }
            initAdapter(copyList)
        } catch (e: Exception) {
            NLog.e("|jake| ...family exception is  . > $e")
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        coreContext.core.removeListener(coreListener)
    }

    private fun initCallErrorMessage() {
        coreContext.callErrorMessageResourceId.observe(
            this
        ) {
            it.consume { message ->
                showSnackBar(message)
            }
        }
    }

    override fun showSnackBar(message: String) {
        Snackbar.make(findViewById(android.R.id.content), message, Snackbar.LENGTH_LONG).show()
    }
}